<?php namespace App\Application;

use App\Exceptions\Item\ItemException;
use App\Models\Item;
use App\Repositories\Item\ItemRepositoryInterface;
use App\Repositories\Order\OrderRepositoryInterface;

class ItemService
{
    /**
     * @var ItemRepositoryInterface
     */
    protected $item_repository;

    public function __construct()
    {
        $this->item_repository = app(ItemRepositoryInterface::class);
    }

    /**
     * 获取信息
     *
     * @param $id
     * @param $user_id
     *
     * @return array
     */
    public function show($id, $user_id)
    {
        $item = $this->item_repository->show((int)$id);
        throw_unless($item, new ItemException(ItemException::NOT_FOUND));

        $info = $this->formatItemInfo($item, true);
        $info['is_paid'] = $this->isAllowView($id, $user_id);
        if ($info['is_paid'] === true) {
            $info['contact'] = $item->contact->only('name', 'phone');
        }

        return $info;
    }

    /**
     * 最新有效的信息列表
     *
     * @param int $per_page
     *
     * @return array
     */
    public function latestValidItems($per_page = 10)
    {
        $items = $this->item_repository->latestValidItems($per_page);
        $items->load('company', 'project', 'publisher', 'tags');

        $data = [];
        foreach ($items as $item) {
            $data[] = $this->formatItemInfo($item);
        }

        $pager = $items->toArray();
        array_pull($pager, 'data');

        return compact('data', 'pager');
    }

    /**
     * 是否允许查询联系方式
     *
     * @param $item_id
     * @param $user_id
     *
     * @return bool
     */
    public function isAllowView($item_id, $user_id)
    {
        /** @var OrderRepositoryInterface $repository */
        $repository = app(OrderRepositoryInterface::class);

        return $repository->isPaidItem($user_id, $item_id);
    }

    /**
     * 格式化信息
     *
     * @param Item $item
     * @param bool $is_show_tend
     *
     * @return array
     */
    private function formatItemInfo(Item $item, $is_show_tend = false)
    {
        $info = $item->only(['id', 'title', 'department', 'stage', 'price', 'expired_at', 'created_at']);
        $info['created_at'] = (string)$info['created_at'];
        $info['company'] = $item->company ? $item->company->only('id', 'name') : [];
        $info['project'] = $item->project ? $item->project->only('id', 'name') : [];
        $info['publisher'] = $item->publisher ? $item->publisher->only('id', 'name', 'avatar') : [];
        $info['stage'] = $item->stage()->first()->only(['id', 'name']);
        $info['tags'] = $item->tags->map(function ($item) {
            return $item->only('id', 'name');
        });
        if ($is_show_tend) {
            $info['description'] = $item->description;
        }

        return $info;
    }
}
